

// 事件基类 用于事件的注册 触发 移除


export default class EventBase {
   
    public eventMap: Map<string, Map<string,Function>>;
    public constructor() {
        this.eventMap = new Map();
    }

  

    // 注册事件
    public on(target:string,event: string, callback: Function) {
        if (!this.eventMap.has(target)) {
            this.eventMap.set(target, new Map());
        }
        
        const map = this.eventMap.get(target);
        if (!map.has(event)) {
            map.set(event, callback);
        }
    }

    // 触发事件
    public emit(event: string, ...args: any[]) {

        this.eventMap.forEach((map)=>{
            if (map.has(event)) {
                map.get(event)(...args);
            }
        })


        
    }

    // 只对目标节点 触发事件
    public emitTarget(target :string,event: string, ...args: any[]) {
        
        const map = this.eventMap.get(target);
        if(!map){
            return;
        }
      
        if (map.has(event)) {
            map.get(event)(...args);
        }
        
    }

   

    // 移除事件
    public off(target:string,event: string) {
        const map = this.eventMap.get(target);
        if(!map){
            console.log('off event error ',target,event );
            return
        }

        if(map.has(event)){
            map.delete(event);
        }
        
    }


    // 移除target上所有事件
    public offTarget(target: string) {
        if (this.eventMap.has(target)) {
            this.eventMap.delete(target);
        }
    }

    // 移除所有节点的事件
    public offAll(event: string) {
        this.eventMap.forEach(events=>{
            if(events.has(event)){
                events.delete(event);
            }
        })
    }



}